import re

from django.contrib.auth.hashers import make_password,check_password
from django.core.mail import send_mail
from django.shortcuts import render
from rest_framework.views import APIView

from django.conf import settings
from .serializers import *
from .models import Cate, Picture, Carousel, Goods,User,UserToken
from rest_framework.response import Response
from django.core.paginator import Paginator
# 导包加密包
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired
# 第一个参数为django自己的secret_key,第二个参数为有效时长，单位秒
serializer = Serializer(settings.SECRET_KEY, 600)
tonke_serializer = Serializer(settings.SECRET_KEY)
# Create your views here.


class CateApi(APIView):

    def post(self,request):
        cate_data = request.data
        if Cate.objects.filter(cate_name=cate_data["cate_name"]):
            return Response({"msg":"分类名重复","code":400})
        else:
            cate_serializers = CateSerializers(data=cate_data)
            if cate_serializers.is_valid():
                cate_serializers.save()
                return Response({"msg":"ok","code":200})
            else:
                print(cate_serializers.errors)
                return Response({"msg":"添加失败","code":400})

    def get(self,request):
        cate_obj = Cate.objects.all()
        cate_serializers = CateSerializers(cate_obj,many=True)
        return Response(cate_serializers.data)

    def put(self,request):
        cate_id = request.data.get("id")
        cate_obj = Cate.objects.filter(pk=cate_id).first()
        if cate_obj:
            cate_obj.cate_name = request.data.get("cate_name")
            cate_obj.cate_img = request.data.get("cate_img")
            cate_obj.save()
            return Response({"msg":"修改成功","code":200})
        else:
            return Response({"msg":"没有该分类","code":400})

    def delete(self,request):
        cate_id = request.data.get("id")
        cate_obj = Cate.objects.filter(pk=cate_id)
        if cate_obj:
            cate_obj.delete()
            return Response({"msg":"删除成功","code":200})
        else:
            return Response({"msg":"分类不存在","code":400})


class PictureApi(APIView):

    def get(self,request):

        picture_obj = Picture.objects.all()
        picture_serializers = PictureSerializers(picture_obj,many=True)
        return Response(picture_serializers.data)


class GoodsApi(APIView):

    def post(self, request):
        """
            添加商品，
            使用post的方式提交数据
        """
        goods_data = request.data
        if Goods.objects.filter(goods_name=goods_data.get("goods_name")):
            return Response({"msg":"商品重复","code":400})
        else:
            goods_serializers = GoodsSerializers(data=goods_data)
            if goods_serializers.is_valid():
                goods_serializers.save()
                return Response({"msg":"ok", "code":200})
            else:
                print(goods_serializers.errors)
                return Response({"msg":goods_serializers.errors, "code":400})

    def get(self,request):
        """
        展示所有的商品
        序列化，把数据库内容转换为json格式
        """
        goods_data = Goods.objects.all()
        goods_serializers = GoodsSerializers(goods_data,many=True)
        return Response(goods_serializers.data)


class GoodsPage(APIView):
    """
    分页展示商品列表
    """

    def get(self,request,pid,cid):
        goods_data = Goods.objects.filter(cate=cid)
        paginotor = Paginator(goods_data,15)
        page = paginotor.page(pid)
        goods_serializers = GoodsSerializers(page,many=True)
        return Response({
            'data':goods_serializers.data,
            'page_max':paginotor.num_pages,
            'page_list':[i for i in paginotor.page_range]
        })


class UserApi(APIView):
    """
    用户注册
    """
    def post(self,request):
        user_data = request.data
        if User.objects.filter(username=user_data.get("username")):
            return Response({"msg":"已经有该用户","code":400})
        if not re.match(r'[0-9a-zA-z_]{0,19}@(.*?).com', user_data.get("email")):
            return Response({"msg":"邮箱不合法","code":400})
        if user_data.get("password") == user_data.get("password2"):
            user_dict = {
                'username':user_data.get("username"),
                'password':make_password(user_data.get("password")),
                'email':user_data.get("email")
            }
            user_serializers = UserSerializers(data=user_dict)
            if user_serializers.is_valid():
                user_serializers.save()
                user_obj_id = user_serializers.data.get("id")
                token = serializer.dumps({"user_id":user_obj_id}).decode()
                # 像用户发送邮件用来激活账号
                subject = "好又多商城会员"
                message = "欢迎注册好又多商城会员"
                from_email = settings.EMAIL_FROM
                recipient_list = [user_data.get("email")]
                html_message = '<h2>请点击下面链接进行激活商城会员<a href="http://127.0.0.1:8000/app01/userapi/?token={}">激活请点击这里</a></h2>'.format(token)
                send_mail(subject=subject,
                          message=message,
                          from_email=from_email,
                          recipient_list=recipient_list,
                          html_message=html_message)

                return Response({"msg":"ok","code":200})
            else:
                print(user_serializers.errors)
                return Response({"msg":"注册失败","code":400})
        else:
            return Response({"msg":"两次密码不一致","code":400})

    def get(self,request):
        """
        注册成功以后访问此get地址激活账号
        :param request:
        :return:
        """
        try:
            token = request.GET.get("token")
            user_info = serializer.loads(token)
            user_obj = User.objects.filter(pk=user_info.get("user_id"))
            user_obj.update(status=1)
            # user_obj.save()
            return Response({"msg":"ok","code":200})
        except SignatureExpired:
            return Response({"msg":"激活失败","code":400})


class LoginUser(APIView):
    """
    登陆接口，需要参数：用户名，密码
    使用post方式提交
    """
    def post(self,request):
        user_data = request.data
        user_obj = User.objects.filter(username=user_data.get("username")).first()

        if not user_obj.status:
            return Response({"msg":"账户未激活","code":400})
        if user_obj:
            print(user_obj.password)
            if check_password(user_data.get("password"), user_obj.password):
                # 将token值进行加密返回前端，并将加密的token值保存到数据库中
                token = tonke_serializer.dumps(user_obj.id).decode()
                UserToken.objects.update_or_create(user=user_obj,defaults={'token':token})
                return Response({"msg":"ok", "code":200, "token":token})
            else:
                return Response({"msg":"用户名或密码错误","code":400})
        else:
            return Response({"msg":"用户名或密码错误","code":400})









